// pages/funcs/near.js
const App = getApp()
import Util from '../../../utils/util'
const citySelector = requirePlugin('citySelector')
let plugin = requirePlugin('routePlan');

Page({
  data: {
    init: false,

    type: 'mer',

    code: '', //城市行政区划码
    city: '', // 城市名称
    locs: '', // 当前位置
    name: '',

    lng: 0,
    lat: 0,

    markers: [],

    pois: [],
    poi: {
      name: ''
    },
    mapScale: 16,
    polylines: [{
      "points": [
        // { "latitude": 24.479510, "longitude": 118.089480 }, // 厦门市左侧点坐标
        // { "latitude": 24.479513, "longitude": 118.079480 }, // 厦门市右侧点坐标
        // { "latitude": 24.490515, "longitude": 118.069480 }  // 厦门市上方点坐标
      ],
      "color": "#FF0000DD",
      "width": 5,
      "dottedLine": false
    }],
    polygons: [{
      "points": [
        // { "latitude": 24.521497, "longitude": 118.121675 },
        // { "latitude": 24.499833, "longitude": 118.089425 },
        // { "latitude": 24.464206, "longitude": 118.160036 },
        // { "latitude": 24.485382, "longitude": 118.192934 }
      ],
      "strokeColor": "#FF0000DD",
      "fillColor": "#00FF00DD",
      "strokeWidth": 2
    }],
    "circles": [{
      "latitude": 24.453952, // 圆心纬度
      "longitude": 118.080718, // 圆心经度
      "color": "#FF0000DD", // 圆的颜色
      "fillColor": "#00FF00DD", // 圆的填充颜色
      "radius": 1000, // 圆的半径，单位米
      "strokeWidth": 2 // 圆边框的宽度
    }],
    pageType: 'detail', // 页面类型: 详情: detail, 回放: playback, 电子围栏: ele-fence, 区域围栏: area-fence
    playbackInfo: {
      value: 0,
      step: 1,
      speed: '慢', // 速度: 慢, 中, 快
      isStart: false,
      currentIndex: 0,
      data: [
        { "latitude": 24.521497, "longitude": 118.121675 },
        { "latitude": 24.499833, "longitude": 118.089425 },
        { "latitude": 24.464206, "longitude": 118.160036 },
        { "latitude": 24.485382, "longitude": 118.192934 }
      ],
    },
    interval: null,
    fenceEleInfo: {
      type: 0, // 0: 圆形, 1: 多边形
      radius: 200,
      circles: [],
    },
  },
  onLoad(options) {
    console.log('onLoad', options)
    if(options.type){
      this.setData({
        pageType: options.type
      })
    }
    const options1 = {
      code: "350200",
      city: "厦门市",
      locs: "118.089480,24.479510"
    }
    this.setData({
      init: true,
      code: options1.code,
      city: options1.city.replace('市', ''),
      locs: options1.locs,
      lng: parseFloat(options1.locs.split(',')[0]),
      lat: parseFloat(options1.locs.split(',')[1])
    })
    this.execLoadMerchant()
    this.initPlaybackSliderData()
  },
  onShow() {
    const selectedCity = citySelector.getCity() // 选择城市后返回城市信息对象，若未选择返回null
    if (selectedCity) {
      let locs = `${selectedCity.location.longitude},${selectedCity.location.latitude}`
      this.setData({
        code: selectedCity.id,
        city: selectedCity.name,
        locs: locs,
        lng: parseFloat(locs.split(',')[0]),
        lat: parseFloat(locs.split(',')[1])
      })
      this.execLoadMerchant()
    }
  },
  onUnload() {
    citySelector.clearCity()
  },
  doSelectCity() {
    const key = App.Global.QmapKey // 使用在腾讯位置服务申请的key
    const referer = App.Global.Title // 调用插件的app的名称
    // const hotCitys = '' // 用户自定义的的热门城市

    wx.navigateTo({
      url: `plugin://citySelector/index?key=${key}&referer=${referer}`,
    })
  },
  doSearch() {
    if (this.data.type == 'mer') {
      this.execLoadMerchant()
    } else {
      this.execLoadGAS()
    }
  },
  doSelectMarker(e) {
    console.log('doSelectMarker', e)
    this.setData({
      poi: this.data.pois[e.markerId]
    })
  },
  execLoadMerchant() {
    this.setData({
      type: 'mer'
    })
    if (this.data.loadingMerchant || this.data.code == '') {
      return
    }
    // let p = resp.data.items.length > 0 ? resp.data.items[0] : {}
    let mks = []
    mks.push({
      id: 100,
      longitude: 118.089480,
      latitude: 24.480510,
      width: '44px',
      height: '48px',
      // width: '70px',
      // height: '40px',
      iconPath: '/assets/images/car.png',
      // iconPath: '/assets/images/gps/car-detail.png',
      // label: {
      //   content: '我的位置',
      //   padding: 5,
      //   borderWidth: 1,
      //   borderRadius: 2,
      //   fontSize: '14',
      //   bgColor: '#fff'
      // },
      callout: {
        content: '奥迪 A6 2019款',
        padding: 5,
        borderWidth: 1,
        borderRadius: 2,
        fontSize: '14',
        bgColor: '#fff',
        display: 'ALWAYS',
        anchorY: -40
      }
      // customCallout: {
      //   anchorY: 0, // Y轴偏移量
      //   anchorX: 0, // X轴偏移量
      //   display: 'ALWAYS', // 'BYCLICK':点击显示; 'ALWAYS':常显
      // }
    })
    this.setData({
      markers: mks,
      // pois: resp.data.items,
      // poi: p,
      lng: this.data.lng,
      lat: this.data.lat,
    })
    return
    this.data.loadingMerchant = true
    App.doPost({
      uri: '/app/base/biz/merchant/near',
      body: {
        city: this.data.code,
        locs: this.data.locs,
        name: this.data.name,
        size: 50
      },
      fnSucc: resp => {
        let idx = 0
        let mks = resp.data.items.map(p => {
          return {
            id: idx++,
            longitude: parseFloat(p.locs.split(',')[0]),
            latitude: parseFloat(p.locs.split(',')[1]),
            width: '32px',
            height: '48px',
            label: {
              content: p.name,
              padding: 5,
              borderWidth: 1,
              borderRadius: 2,
              fontSize: '14',
              bgColor: '#fff'
            }
          }
        })

      },
      fnComp: () => {
        this.data.loadingMerchant = false
      }
    })
  },
  execLoadGAS() {
    this.setData({
      type: 'gas'
    })
    if (this.data.loadingMerchant || this.data.code == '') {
      return
    }
    this.data.loadingMerchant = true
    App.doPost({
      uri: '/app/base/biz/merchant/gas/near',
      body: {
        city: this.data.code,
        locs: this.data.locs,
        name: this.data.name,
        size: 50
      },
      fnSucc: resp => {
        let idx = 0
        let mks = resp.data.items.map(p => {
          return {
            id: idx++,
            longitude: parseFloat(p.locs.split(',')[0]),
            latitude: parseFloat(p.locs.split(',')[1]),
            width: '32px',
            height: '48px',
            label: {
              content: p.name,
              padding: 5,
              borderWidth: 1,
              borderRadius: 2,
              fontSize: '14',
              bgColor: '#fff'
            }
          }
        })
        // let p = resp.data.items.length > 0 ? resp.data.items[0] : {}
        this.setData({
          markers: mks,
          // pois: resp.data.items,
          // poi: p,
          lng: p.locs ? parseFloat(p.locs.split(',')[0]) : this.data.lng,
          lat: p.locs ? parseFloat(p.locs.split(',')[1]) : this.data.lat,
        })
      },
      fnComp: () => {
        this.data.loadingMerchant = false
      }
    })
  },
  toNowloc() {
    this.setData({
      lng: parseFloat(this.data.locs.split(',')[0]),
      lat: parseFloat(this.data.locs.split(',')[1])
    })
  },
  toMchCars(e) {
    let poi = e.currentTarget.dataset.poi
    console.log(poi)
    wx.redirectTo({
      url: `/pages/home/mcar?mchid=${poi.id}&clkid=`,
      fail: (res) => {
        console.log(res)
      }
    })
  },
  doNav() {
    if (!this.data.poi.locs) {
      Util.Notify.warn(`该店没有设置具体位置，无法导航`)
      return
    }
    let lat = this.data.poi.locs.split(',')[1]
    let lng = this.data.poi.locs.split(',')[0]
    wx.openLocation({
      latitude: parseFloat(lat),
      longitude: parseFloat(lng),
      name: this.data.poi.name,
      address: this.data.poi.addr,
      scale: 18
    })
  },

  doTel() {
    if (!this.data.poi.tel) {
      Util.Notify.warn(`该店没有设置联系电话，无法拨号`)
      return
    }
    wx.makePhoneCall({
      phoneNumber: this.data.poi.tel
    })
  },
  goToCarLocation() {
    const key = App.Global.QmapKey // 使用在腾讯位置服务申请的key
    const referer = App.Global.Title // 调用插件的app的名称
    let endPoint = JSON.stringify({  //终点
      'name': '北京西站',
      'latitude': 24.480510,
      'longitude': 118.089480
    });
    wx.navigateTo({
      url: 'plugin://routePlan/index?key=' + key + '&referer=' + referer + '&endPoint=' + endPoint
    });
  },
  doCurrentLocation() {
    wx.getLocation({
      type: 'gcj02',
      success: (res) => {
        let locs = `${res.longitude},${res.latitude}`
        this.setData({
          locs: locs,
          lng: res.longitude,
          lat: res.latitude
        })
        this.execLoadMerchant()
      }
    })
  },
  goToSetting() {
    wx.navigateTo({
      url: '/pages/gps/cardetail/detail',
    })
  },
  playbackInfoValueChange(e) {
    this.setData({
      'playbackInfo.value': e.detail.value
    })
  },
  playbackInfoSpeedChange() {
    let speed = this.data.playbackInfo.speed
    if (this.data.playbackInfo.speed == '慢') {
      speed = '中'
    } else if (this.data.playbackInfo.speed == '中') {
      speed = '快'
    } else {
      speed = '慢'
    }
    this.setData({
      'playbackInfo.speed': speed
    })
  },
  resetPlaybackData() {
    this.setData({
      'playbackInfo.value': 0,
      'playbackInfo.currentIndex': 0,
      'playbackInfo.isStart': false,
      'playbackInfo.currentIndex': 0,
      'polylines[0].points': [],
    })
  },
  initPlaybackSliderData() {
    const data = this.data.playbackInfo.data
    console.log('data', data)
    // 根据数据计算 step， max 100
    const step = Math.ceil(100 / data.length)
    this.setData({
      'playbackInfo.step': step,
      'playbackInfo.value': 0,
      'playbackInfo.isStart': false,
      'playbackInfo.speed': '慢',
      'playbackInfo.currentIndex': 0,
    })
    this.initInterval()
  },
  handleSilderChange() {
    console.log('handleSilderChange')
    const playbackInfo = this.data.playbackInfo

    let value = playbackInfo.value + playbackInfo.step
    if(value >= 100) {
      value = 100
      this.interval.pause()
      this.setData({
        'playbackInfo.isStart': false
      })
    }
    const polygonsPoints = this.data.polylines[0].points
    polygonsPoints.push(playbackInfo.data[playbackInfo.currentIndex])
    console.log('polygonsPoints', polygonsPoints)
    this.setData({
      'polylines[0].points': polygonsPoints,
      markers: [this.getCarMarker(playbackInfo.data[playbackInfo.currentIndex])]
    })
    this.setData({
      'playbackInfo.value': value,
      'playbackInfo.currentIndex': playbackInfo.currentIndex + 1
    })
  },
  doStartOrStopPlayback() {
    const playbackInfo = this.data.playbackInfo
    this.setData({
      'playbackInfo.isStart': !playbackInfo.isStart
    })
    if (playbackInfo.isStart) {
      if(playbackInfo.currentIndex >= playbackInfo.data.length) {
        this.resetPlaybackData()
      }
      this.interval.start()
      this.setData({
        lng: playbackInfo.data[playbackInfo.currentIndex].longitude,
        lat: playbackInfo.data[playbackInfo.currentIndex].latitude
      })
    } else {
      this.interval.pause()
    }
  },
  getCarMarker({longitude, latitude}){
    const marker = {
      id: 100,
      longitude: longitude,
      latitude: latitude,
      width: '35px',
      height: '20px',
      iconPath: '/assets/images/gps/car-detail.png',
      rotate: 180,
      // callout: {
      //   content: '奥迪 A6 2019款',
      //   padding: 5,
      //   borderWidth: 1,
      //   borderRadius: 2,
      //   fontSize: '14',
      //   bgColor: '#fff',
      //   display: 'ALWAYS'
      // }
    }
    return marker
  },
  initInterval() {
    class Interval {
      constructor({
        intervalFrequency = 10000,
        handler,
      } = {
        }) {
        if (typeof intervalFrequency !== 'number' || intervalFrequency <= 0) {
          throw new Error('Invalid param `intervalFrequency`, must be an integer greater than 0')
        }
        if (typeof handler !== 'function' || !(handler instanceof Function)) {
          throw new Error('Invalid param `handler`, must be a function')
        }

        this.intervalFrequency = intervalFrequency
        this.handler = handler
        this.interval = null
        this.paused = false
      }

      async IntervalCallback() {
        this.clean()
        if (this.paused) {
          return
        }
        try {
          await this.handler()
        } catch (err) {
          console.log('err', err)
        }
        if (!this.paused) {
          this.create()
        }
      }

      clean() {
        clearInterval(this.interval)
        this.interval = null
      }

      create() {
        const that = this
        if (that.interval === null) {
          that.interval = setInterval(async () => {
            await that.IntervalCallback()
          }, that.intervalFrequency)
        }
      }

      start() {
        if (this.paused) {
          this.paused = false
        }
        this.create()
      }

      pause() {
        if (!this.paused) {
          this.paused = true
          this.clean()
        }
      }
      editFrequency(intervalFrequency) {
        this.intervalFrequency = intervalFrequency
      }
    }
    this.interval = new Interval({
      intervalFrequency: 1000,
      handler: this.handleSilderChange
    })
  },
  fenceTypeChange(e) {
    this.setData({
      'fenceEleInfo.type': e.currentTarget.dataset.type
    })
  },
  feencefoRadiusChange(e) {
    const radius = e.detail.value
    let mapScale = 16
    // 判断需不需要调整缩放级别
    if (radius < 500) {
      mapScale = 16
    } else if (radius < 1000) {
      mapScale = 15
    } else if (radius < 2000) {
      mapScale = 14
    }else if (radius < 3000) {
      mapScale = 13
    } else if (radius <= 5000) {
      mapScale = 12
    }
    const circle = {
      "latitude": 24.479510, // 圆心纬度
      "longitude": 118.089480, // 圆心经度
      "color": "#FF0000DD", // 圆的颜色
      "fillColor": "#FF0000A0", // 圆的填充颜色
      "radius": radius, // 圆的半径，单位米
      "strokeWidth": 2 // 圆边框的宽度
    }
    
    this.setData({
      'fenceEleInfo.radius': radius,
      circles: [circle],
      mapScale: mapScale
    })
  },
})